import config from "./config"
import compose from "koa-compose"

import cors from "@koa/cors"
import jwt from "koa-jwt"
import ratelimit from "koa2-ratelimit"
import helmet from "koa-helmet"
import compress from "koa-compress"
import conditional from "koa-conditional-get"
import etag from "koa-etag"
import router from "./router"

import before_interceptor from "./middlewares/interceptor/before.interceptor"
import cache_interceptor from "./middlewares/interceptor/cache.interceptor"
import call_interceptor from "./middlewares/interceptor/call.interceptor"
import after_interceptor from "./middlewares/interceptor/after.interceptor"

class middleware {
    constructor() {
        this.middlewares = [];
        this.config = config;
        this.router = router;
        this.ratelimit = ratelimit.RateLimit;
        return this.install_interceptor().then(() => this.compose());
    }

    async install_interceptor() {
        // 安装after before拦截器中间件
        this.config = await this.config;
        this.router = await this.router;
        for (let i2 of this.router) {
            for (let i of i2.router.stack) {
                i.stack.unshift(before_interceptor);
                i.stack.splice(5, 0, cache_interceptor);
                i.stack.splice(6, 0, call_interceptor);
                i.stack.push(after_interceptor);
            }
        }
    }

    async compose() {
        //合并中间件
        this.ratelimit = this.ratelimit.middleware(this.config.ratelimit);
        this.middlewares = [
            cors({}),
            jwt(
                {secret: this.config.jwt.secret}
            ).unless(this.config.router.jwtRouteUnLessList),
            this.ratelimit, helmet(), compress(), conditional(), etag(), ...this.router
        ];
        return compose(this.middlewares)
    }
}

export default new middleware();